package com.example.AIstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.AIstudy.DTO.RecordDTO;
import com.example.AIstudy.DTO.RedoRecordDTO;
import com.example.AIstudy.dao.CompositionDao;
import com.example.AIstudy.dao.FalseReasonDao;
import com.example.AIstudy.dao.RedoRecordDao;
import com.example.AIstudy.dao.TranslateDao;
import com.example.AIstudy.domain.CuoTiJi;
import com.example.AIstudy.domain.Question;
import com.example.AIstudy.domain.RedoRecord;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.CuoTiJiService;
import com.example.AIstudy.service.RedoRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RedoRecordServiceImpl extends ServiceImpl<RedoRecordDao, RedoRecord> implements RedoRecordService {

    @Autowired
    RedoRecordDao redoRecordDao;
    @Autowired
    FalseReasonDao falseReasonDao;
    @Autowired
    TranslateDao translateDao;
    @Autowired
    CompositionDao compositionDao;
    @Autowired
    CuoTiJiService cuoTiJiService;

    public List<RedoRecordDTO> queryLastTimeRedoDetail() throws AIstudyException {
        try{
            return redoRecordDao.queryLastTimeRedoDetail();
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.QUERY_ERROR,"查询近期错题巩固信息失败");
        }
    }
    public IPage<RedoRecordDTO> queryRedoRecord(Map<String,Object> condition, Integer pageNum, Integer pageSize){
        IPage page = new Page(pageNum, pageSize);
        QueryWrapper<RedoRecordDTO> qw = new QueryWrapper<>();
        //确保同一道阅读大题只查出来一次
        qw.and(wq -> {
            // 拼接sql
            wq.isNotNull("k.sonProID")
                    .or()
                    .ne("k.category","yuedu");
        });
        qw.eq(condition.containsKey("stuID"), "k.stuID", condition.get("stuID"));
        if(condition.containsKey("category")){
            List<String>category= (List<String>) condition.get("category");
            qw.and(wq -> {
                // 拼接sql
                wq.in("category",category);
            });
        }
//        qw.in(condition.containsKey("category"), "k.category", condition.get("category"));
        //学生查询问题信息的时候可以筛选
//        qw.in(condition.containsKey("falseReasonIDs"), "k.falseReasonID", condition.get("falseReasonIDs"));
        qw.ge(condition.containsKey("minTime"), "p.redoTime", condition.get("minTime"));
        qw.le(condition.containsKey("maxTime"), "p.redoTime", condition.get("maxTime"));
//        if(condition.containsKey("order")){
//            String order= (String) condition.get("order");
//            if(order.equals("ASC")){
//                qw.orderByAsc("p.redoTime");
//            }
//            else{
//                qw.orderByDesc("p.redoTime");
//            }
//        }
//        //获取每条的记录，并且分析每道错题的原因
//        IPage<RedoRecordDTO>page1=redoRecordDao.queryRedoRecord(page, qw);
//        List<RedoRecordDTO>list=page1.getRecords();
//        int size=list.size();
//        for(int i=0;i<size;i++){
//            RedoRecordDTO redoRecordDTO=list.get(i);
//            redoRecordDTO.setFalseReason(falseReasonDao.selectById(redoRecordDTO.getFalseReasonID()).getFalseReason());
//        }
        return redoRecordDao.queryRedoRecord(page, qw);
    }

    public RedoRecord getRecordDetail(Integer recordID) throws AIstudyException{
        try {
            RedoRecord record=redoRecordDao.selectById(recordID);
            if(record.getRedoTranslationID()!=null){
                record.setTranslateDetail(translateDao.selectById(record.getRedoTranslationID()));
            }
            if(record.getRedoCompositionID()!=null) {
                record.setCompositionDetail(compositionDao.selectById(record.getRedoCompositionID()));
            }
            if(record.getRedoSonProID()!=null){
                //获取子阅读题的巩固记录ID（根据巩固时的ID来获取）
                String[] sonlistStr = record.getRedoSonProID().split(",");
                List<Integer> sonList = new ArrayList<>();
                int sizeSon = sonlistStr.length;
                for (int j = 0; j < sizeSon; j++) {
                    sonList.add(Integer.valueOf(sonlistStr[j]));
                }
                //获取子阅读题的巩固记录
                record.setRedoRecords(redoRecordDao.selectBatchIds(sonList));
                RedoRecord record1=new RedoRecord();
                //进行record的深复制
                record1.setId(record.getId());
                record1.setCuotiID(record.getCuotiID());
                record1.setRedoTime(record.getRedoTime());
                record1.setRedoAnswer(record.getRedoAnswer());
                record1.setRedoRight(record.getRedoRight());
                record1.setRedoScore(record.getRedoScore());
                record1.setRedoAIComment(record.getRedoAIComment());
                record1.setRedoUserComment(record.getRedoUserComment());
                record1.setFalseReason(record.getFalseReason());
                record.getRedoRecords().add(0,record1);
                //根据所有的巩固记录来封装所有的题目
                List<RedoRecord>redoRecords=record.getRedoRecords();
                int size2=redoRecords.size();
                List<Integer>cuotiIDlist=new ArrayList<>();
                for(int i=0;i<size2;i++){
                    cuotiIDlist.add(redoRecords.get(i).getCuotiID());
                }
                record.setCuoTiList(cuoTiJiService.listByIds(cuotiIDlist));
            }
            return record;
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.QUERY_ERROR,"查询错题巩固详细信息出错");
        }
    }

    //获取巩固记录，以错题的json返回
    public CuoTiJi getRecordDetailWithCuotiJson(Integer recordID) throws AIstudyException{
        try {
            RedoRecord record=redoRecordDao.selectById(recordID);
            //根据错题的id获取错题的信息
            CuoTiJi cuoTiJi=cuoTiJiService.getCuoTiDetailByID(record.getCuotiID());
            //封装除了阅读之外的信息，将巩固的信息封装在错题中
            if(cuoTiJi.getCategory()!="yuedu"){
                fengzhaungcuotiByRedoRecord(cuoTiJi, record);
            }
            //封装阅读的信息
            if(record.getRedoSonProID()!=null){
                //获取子阅读题的巩固记录ID（根据巩固时的ID来获取）
                String[] sonlistStr = record.getRedoSonProID().split(",");
                List<Integer> sonList = new ArrayList<>();
                int sizeSon = sonlistStr.length;
                for (int j = 0; j < sizeSon; j++) {
                    sonList.add(Integer.valueOf(sonlistStr[j]));
                }
                //获取子阅读题的巩固记录
                List<RedoRecord>sonRecords=redoRecordDao.selectBatchIds(sonList);
                //获取错题集，一一封装
                List<CuoTiJi>cuoTiJis=cuoTiJi.getCuoTiList();
                //封装阅读的第一个cuoti
                cuoTiJis.set(0,fengzhaungcuotiByRedoRecord(cuoTiJis.get(0), record));
                int size=sonRecords.size();
                int size2=cuoTiJis.size();
                for(int i=0;i<size;i++){
                    for(int j=1;j<size2;j++){
                        //找到与重做记录的错题id相同的错题，避免出现次序的混乱
                        if(sonRecords.get(i).getCuotiID()==cuoTiJis.get(j).getId()){
                            //进行答案的封装
                            cuoTiJis.set(j,fengzhaungcuotiByRedoRecord(cuoTiJis.get(j), sonRecords.get(i)));
                            break;
                        }
                    }
                }
            }
            return cuoTiJi;
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.QUERY_ERROR,"查询错题巩固详细信息出错");
        }
    }

    //将巩固记录的信息封装到错题集中
    public CuoTiJi fengzhaungcuotiByRedoRecord(CuoTiJi cuoTiJi,RedoRecord record){
        cuoTiJi.setRedoID(record.getId());
        cuoTiJi.setScore(record.getRedoScore());
        cuoTiJi.setRight(record.getRedoRight());
        cuoTiJi.setInsertTime(record.getRedoTime());
        cuoTiJi.setFalseReason(record.getFalseReason());
        cuoTiJi.setStuAnswer(record.getRedoAnswer());
        cuoTiJi.setAiComment(record.getRedoAIComment());
        cuoTiJi.setUserComment(record.getRedoUserComment());
        //封装阅读和作文的详细评价信息
        if(record.getRedoTranslationID()!=null){
            cuoTiJi.setTranslateDetail(translateDao.selectById(record.getRedoTranslationID()));
        }
        if(record.getRedoCompositionID()!=null) {
            cuoTiJi.setCompositionDetail(compositionDao.selectById(record.getRedoCompositionID()));
        }
        return cuoTiJi;
    }

    //插入一个记录并且查询详细信息
    @Transactional(rollbackFor = AIstudyException.class)
    public RedoRecord insertRedoRecord(RedoRecord record)throws AIstudyException{
        try{
            redoRecordDao.insertRedoRecord(record);
            return  getRecordDetail(record.getId());
        }catch (Exception e){

            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"增加错题巩固详细信息出错");
        }
    }

    //插入一个记录并且查询详细信息，以cuotiji的json格式返回
    @Transactional(rollbackFor = AIstudyException.class)
    public CuoTiJi insertRedoRecordGetCuotiJson(RedoRecord record)throws AIstudyException{
        try{
            redoRecordDao.insertRedoRecord(record);
            return  getRecordDetailWithCuotiJson(record.getId());
        }catch (Exception e){

            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"增加错题巩固详细信息出错");
        }
    }

    //插入多条记录
    @Transactional(rollbackFor = AIstudyException.class)
    public RedoRecord insertRedoRecords(List<RedoRecord> records)throws AIstudyException{
        try{
           int size=records.size();
            StringBuilder sonProID=new StringBuilder();
           for (int i=1;i<size;i++){
               redoRecordDao.insertRedoRecord(records.get(i));
               sonProID.append(records.get(i).getId());
               sonProID.append(",");
           }
           records.get(0).setRedoSonProID(sonProID.toString().substring(0, sonProID.length()-1));
            redoRecordDao.insertRedoRecord(records.get(0));
            return getRecordDetail(records.get(0).getId());
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"增加错题巩固详细信息出错");
        }
    }
    //插入多条记录
    @Transactional(rollbackFor = AIstudyException.class)
    public CuoTiJi insertRedoRecordsGetCuotiJson(List<RedoRecord> records)throws AIstudyException{
        try{
            int size=records.size();
            StringBuilder sonProID=new StringBuilder();
            for (int i=1;i<size;i++){
                redoRecordDao.insertRedoRecord(records.get(i));
                sonProID.append(records.get(i).getId());
                sonProID.append(",");
            }
            //封装巩固的子题id
            records.get(0).setRedoSonProID(sonProID.toString().substring(0, sonProID.length()-1));
            redoRecordDao.insertRedoRecord(records.get(0));
            return getRecordDetailWithCuotiJson(records.get(0).getId());
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"增加错题巩固详细信息出错");
        }
    }

    //更新用户的错因标签和标注信息
    public void updateRecordUserComment(RedoRecord record) throws AIstudyException{
        try{
            //非阅读题 直接增加
            if(record.getRedoRecords()==null){
                redoRecordDao.updateById(record);
            }else{
                //阅读题 逐个增加
                List<RedoRecord>records=record.getRedoRecords();
                int size=records.size();
                for(int i=0;i<size;i++){
                    redoRecordDao.updateById(records.get(i));
                }
            }
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"更新重做记录出错");
        }
    }
}
